package com.GroupSix.service;

import com.GroupSix.dao.ExamAnswerDao;
import com.GroupSix.dao.ExamPaperDao;
import com.GroupSix.dao.QuestionBankDao;
import com.GroupSix.dao.WrongQuestionDao;
import com.GroupSix.entity.ExamAnswerEntity;
import com.GroupSix.entity.ExamPaperEntity;
import com.GroupSix.entity.QuestionBankEntity;
import com.GroupSix.entity.WrongQuestionEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("examAnswerService")
@Slf4j

public class ExamAnswerServiceImpl extends ServiceImpl<ExamAnswerDao, ExamAnswerEntity> implements ExamAnswerService {

    @Autowired
    private ExamAnswerDao examAnswerDao;

    @Autowired
    private QuestionBankDao questionBankDao;

    @Autowired
    private ExamPaperDao examPaperDao;

    @Autowired
    private WrongQuestionDao wrongQuestionDao;

    @Autowired WrongQuestionService wrongQuestionService;
//提交试卷
    @Override
    @Transactional
    public void submitExam(ExamAnswerEntity answer) {
        // 1. 获取试卷信息
        ExamPaperEntity paper = examPaperDao.selectById(answer.getExamId());

        if(paper == null) {
            throw new RuntimeException("试卷不存在");
        }

        // 2. 检查考试时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = paper.getStartTime();
        LocalDateTime endTime = paper.getEndTime();
        //将时间数据格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 直接比较时间
        if (now.isBefore(startTime)) {

            long minutesUntilStart = Duration.between(now, startTime).toMinutes();

            throw new RuntimeException(String.format("考试还未开始，距离开始还有 %d 分钟，开始时间：%s",
                    minutesUntilStart, startTime.format(formatter)));
        }
        if (now.isAfter(endTime)) {
            throw new RuntimeException("考试已结束，结束时间：" + endTime.format(formatter));
        }
        // 4. 如果时间正常，继续处理提交
        answer.setCreateTime(now);
        answer.setSubmitTime(now);
        Double score = calculateScore(answer);
        answer.setScore(score);
        answer.setUpdateTime(LocalDateTime.now());
        // 5. 保存答案
        this.save(answer);
    }
    // 添加一个辅助方法来检查剩余时间
    public Map<String, Object> checkExamTime(Integer examId) {
        Map<String, Object> result = new HashMap<>();

        ExamPaperEntity paper = examPaperDao.selectById(examId);

        if(paper == null) {
            throw new RuntimeException("试卷不存在");
        }

        LocalDateTime now = LocalDateTime.now();

        LocalDateTime endTime = paper.getEndTime();

        Duration remainingTime = Duration.between(now, endTime);


        result.put("考试状态", now.isBefore(endTime) ? "进行中" : "已结束");
        result.put("剩余时间", remainingTime.toMinutes());
        result.put("结束时间", endTime);

        return result;
    }
    public Double calculateScore(ExamAnswerEntity answer) {
        Double totalScore = 0.0;

        // 1. 从试卷获取题号数组
        ExamPaperEntity paper = examPaperDao.selectById(answer.getExamId());
        if(paper == null) {
            throw new RuntimeException("试卷不存在");
        }
        Integer[] questionIds = paper.getQuestions();

        // 2. 遍历每道题进行评分
        String[] studentAnswers = answer.getStudentAnswers();
        for (int i = 0; i < questionIds.length; i++) {
            // 获取正确答案
            QuestionBankEntity question = questionBankDao.selectById(questionIds[i]);
            if (question != null && studentAnswers[i].equals(question.getQsanswer())) {
                totalScore += question.getQsscore();  // 答对加分
            }else{
                QueryWrapper<WrongQuestionEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id", answer.getStudentId());
                wrapper.eq("question_id", questionIds[i]);
                WrongQuestionEntity wrongQuestion = wrongQuestionDao.selectOne(wrapper);
                if(null !=wrongQuestion){
                    wrongQuestion.setCountIncorrect(wrongQuestion.getCountIncorrect() + 1);
                    //更新错误次数
                    wrongQuestionService.updateById(wrongQuestion);
                }else{
                // 保存错题
                      wrongQuestionService.addWrongQuestionManually(answer.getStudentId(), Long.valueOf(questionIds[i]), "考试错题");
                }


            }
        }

        return totalScore;
    }

    @Override
    public ExamAnswerEntity getAnswer(Integer answerId) {
        QueryWrapper<ExamAnswerEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", answerId);
        return baseMapper.selectOne(wrapper);
    }

    //分页查询答卷
    @Override
    public IPage<ExamAnswerEntity> list(ExamAnswerEntity examAnswerEntity, Integer pageNo, Integer pageSize) {
        LambdaQueryWrapper<ExamAnswerEntity> wrapper = Wrappers.lambdaQuery();

        // 添加查询条件，根据传入的examAnswerEntity进行条件过滤
        if (examAnswerEntity.getExamId() != null) {
            wrapper.eq(ExamAnswerEntity::getExamId, examAnswerEntity.getExamId());
        }
        if (StringUtils.hasText(String.valueOf(examAnswerEntity.getStudentId()))) {
            wrapper.eq(ExamAnswerEntity::getStudentId, examAnswerEntity.getStudentId());
        }

        // 设置默认分页参数
        int currentPage = 1;
        int limit = 10;
        if (pageNo != null && pageNo > 0) {
            currentPage = pageNo;
        }
        if (pageSize != null && pageSize > 0) {
            limit = pageSize;
        }

        // 创建分页对象
        IPage<ExamAnswerEntity> page = Page.of(currentPage, limit);

        // 执行分页查询
        return examAnswerDao.selectPage(page, wrapper);
    }

}

